<template>
	<view class="dynamic-bg">
		<!-- 顶部栏 -->
		<view class="top-bar">
			<text class="title">广场</text>
			<u-icon name="more-dot-fill" size="28" color="#333" class="more-btn" />
		</view>
		<!-- 动态列表区 -->
		<view class="list-section" v-if="globalConfig.examine != 1">
			<view v-if="dynamicList.length === 0">
				<u-empty text="还没有小伙伴发布动态，快去发布第一条吧~" mode="news" />
			</view>
			<view v-else>
				<view v-for="item in dynamicList" :key="item.id" class="dynamic-card">
					<view class="card-header" @click="goDetail(item)">
						<u-avatar :src="globalConfig.site_url+item.user_info.image || ''" size="40" />

						<view class="user-info">
							<text class="nickname">{{ item.user_info.nickname }}</text>
							<text class="time">{{ item.createtime }}</text>
						</view>
					</view>
					<view class="card-content" @click="goDetail(item)">{{ item.info }}</view>
					<view v-if="item.images && item.images.length" class="card-images" @click="goDetail(item)">
						<image v-for="(img, idx) in item.images" :key="idx" :src=" globalConfig.site_url+img"
							mode="aspectFill" class="card-img" />
					</view>
					<view class="card-footer">
						<text class="location">{{ item.area_name }}</text>
						<view class="actions">
							<u-icon name="thumb-up" size="24" :color="item.liked ? '#ff4d4f' : '#ff4df'"
								@click.stop="handleLike(item)" />
							<text>{{ item.likes_count }}</text>
							<u-icon name="chat" size="24" color="#7bdffe" style="margin-left: 24rpx;"
								@click="goDetail(item)" />
							<text>{{ item.comments_count }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 发布入口 -->
		<view class="fab-btn">
			<u-button type="primary" shape="circle" icon="plus" @click="goPublish">发布</u-button>
		</view>


		<!-- uView登录弹窗 (from shop-list.vue) -->
		<u-popup v-model="showLoginPopup" mode="center" border-radius="16" width="600rpx" :mask-close-able="true"
			@close="closeLoginPopup">
			<view class="login-popup">
				<view class="popup-header">
					<view class="popup-title">登录</view>
					<view class="popup-close" @click="closeLoginPopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="login-methods">
					<u-button type="success" shape="round" :loading="wechatLoading" @click="handleWechatLogin"
						:custom-style="{ backgroundColor: '#07c160', borderColor: '#07c160', marginBottom: '20rpx' }">
						<u-icon name="weixin-fill" color="#fff" size="20" style="margin-right: 10rpx"></u-icon>
						{{ wechatLoading ? '登录中...' : '微信登录' }}
					</u-button>
				</view>

				<view class="login-tips">
					<u-checkbox v-model="agreePolicy" shape="circle" active-color="#007aff" :size="32"
						style="margin-right: 10rpx;" />
					<text class="tips-text">我已阅读并同意</text>
					<text class="link-text" @click="showPrivacy('agreement')">《用户协议》</text>
					<text class="tips-text">和</text>
					<text class="link-text" @click="showPrivacy('policy')">《隐私政策》</text>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getPosts
	} from '@/api/partner.js'
	import {
		saveLikes
	} from '@/api/dynamic.js'
	import {
		mapGetters,
		mapState
	} from 'vuex';
	import {
		checkLoginStatus,
		wechatMiniLogin
	} from '@/common/auth.js';
	export default {
		name: 'DynamicIndex',
		data() {
			return {
				showLoginPopup: false,
				agreePolicy: false,
				wechatLoading: false,
				page: 1,
				pageSize: 10,
				hasMore: true,
				// 动态列表数据
				dynamicList: []
			}
		},
		computed: {
			...mapGetters(['getUserInfo']),
			// 使用mapState直接访问state
			...mapState({
				globalConfig: state => state.config,
				userLocation: state => state.location,
			})
		},
		onReachBottom() {
			if (this.hasMore) {
				this.page++;
				this.getDynamicList();
			}
		},
		onShow() {
			this.getDynamicList();
			uni.$on('refreshDynamicIndex', () => {
				this.getDynamicList();
			});
		},
		onUnload() {
			uni.$off('refreshDynamicIndex');
		},
		mounted() {
			this.getDynamicList()
		},
		methods: {
			showPrivacy(type) {
				// 获取协议标题
				let title = type === 'agreement' ? '用户协议' : '隐私政策';
				// 获取全局配置里的 yinsi 内容
				const yinsi = this.globalConfig?.yinsi || '';
				uni.navigateTo({
					url: `/pages/common/rich-text?title=${encodeURIComponent(title)}&content=${encodeURIComponent(yinsi)}`
				});
			},
			async handleWechatLogin() {
				// 判断有没有勾选隐私
				if (!this.agreePolicy) {
					this.$u.toast('请先勾选同意《用户协议》和《隐私政策》');
					return;
				}
				if (this.wechatLoading) return;
				this.wechatLoading = true;
				try {
					const result = await wechatMiniLogin();
					if (result.success) {
						this.$store.dispatch('fetchUserInfoAction');
						this.closeLoginPopup();
						this.$u.toast('登录成功');
						this.getDynamicList();
					} else {
						throw new Error(result.message || '登录失败');
					}
				} catch (error) {
					this.$u.toast(error.message || '登录操作失败');
				} finally {
					this.wechatLoading = false;
				}
			},
			closeLoginPopup() {
				this.showLoginPopup = false;
				this.wechatLoading = false;
			},
			onPullDownRefresh() {
				this.getDynamicList();
			},
			async getDynamicList() {
				try {
					const res = await getPosts({
						page: this.page,
						pageSize: this.pageSize
					});
					if (res.data && res.data.code === 1) {
						let newData = res.data.data.list || [];
						newData = newData.map(item => ({
							...item,
							liked: item.liked || false
						}));
						this.dynamicList = this.page === 1 ? newData : this.dynamicList.concat(newData);
						this.hasMore = newData.length >= this.pageSize;
					} else {
						uni.showToast({
							title: res.msg || '获取动态失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取动态列表失败:', error);
					uni.showToast({
						title: '网络错误，无法获取动态',
						icon: 'none'
					});
				} finally {
					uni.stopPullDownRefresh();
				}
			},
			goDetail(item) {
				console.log(item, 'goDetail');
				uni.navigateTo({
					url: `/pages/dynamic/comment?id=${item.id}`
				})
			},
			async goPublish() {
				const isLoggedIn = await checkLoginStatus();
				if (!isLoggedIn) {
					this.showLoginPopup = true;
					return;
				}
				uni.navigateTo({
					url: '/pages/dynamic/publish'
				});
			},
			async handleLike(item) {
				const newType = item.liked ? 2 : 1;
				// 乐观更新
				item.liked = !item.liked;
				item.likes_count += newType === 1 ? 1 : -1;

				try {
					const res = await saveLikes({
						posts_id: item.id,
						type: newType
					});
					if (res.data && res.data.code !== 1) {
						// 操作失败，回滚
						item.liked = !item.liked;
						item.likes_count += newType === 1 ? -1 : 1;
						uni.showToast({
							title: res.data.msg || '点赞失败',
							icon: 'none'
						});
					}
				} catch (error) {
					// 网络错误，回滚
					item.liked = !item.liked;
					item.likes_count += newType === 1 ? -1 : 1;
					uni.showToast({
						title: '网络错误，无法操作',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style scoped>
	.dynamic-bg {
		min-height: 100vh;
		background: #18181a;
		padding-top: 110rpx;
		position: relative;
	}

	.top-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		background: transparent;
	}

	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #7bdffe;
	}

	.more-btn {
		margin-left: 16rpx;
	}

	.list-section {
		margin: 32rpx 0 0 0;
		padding: 0 24rpx;
		padding-bottom: 100rpx;
	}

	.dynamic-card {
		background: #23232b;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(156, 108, 254, 0.08);
		margin-bottom: 32rpx;
		padding: 32rpx 24rpx 24rpx 24rpx;
		transition: box-shadow 0.2s;
		color: #fff;
	}

	.card-header {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.user-info {
		display: flex;
		flex-direction: column;
		margin-left: 16rpx;
	}

	.nickname {
		font-size: 28rpx;
		font-weight: bold;
		color: #fff;
	}

	.time {
		font-size: 22rpx;
		color: #b0b0b0;
		margin-top: 4rpx;
	}

	.card-content {
		font-size: 28rpx;
		color: #fff;
		margin-bottom: 16rpx;
	}

	.card-images {
		display: flex;
		gap: 12rpx;
		margin-bottom: 16rpx;
	}

	.card-img {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		object-fit: cover;
	}

	.card-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.location {
		font-size: 22rpx;
		color: #7bdffe;
	}

	.actions {
		display: flex;
		align-items: center;
		color: #7bdffe;
		font-size: 24rpx;
	}

	.fab-btn {
		position: fixed;
		right: 48rpx;
		bottom: 180rpx;
		z-index: 10;
	}
</style>